import TjTable from '@/pages/ETrade/components/TjTable';
import { TjForm, TjSlideSelect } from '@/tjComponents';
import TjMarketingUnit from '@/tjComponents/TjMarketingUnit';
import { DatePicker, Form, Input, InputNumber, Select } from 'antd';
import React, { useState, useEffect } from 'react';
import _ from 'lodash';
import { arrToFormData, formDataToArr, limitDecimals } from '../../helper';
import type { ArtColumn } from 'ali-react-table';
import './index.less';

const columns: ArtColumn[] = [
  {
    name: '月份',
    code: 'month',
    align: 'center',
  },
  {
    name: '当月是否为现货策略场站',
    code: 'spotStrategyStation',
    align: 'center',
    render: (value: any, row: any) => {
      return (
        <Form.Item name={`spotStrategyStation@${row.month}`}>
          <TjSlideSelect
            defaultValue={false}
            items={[
              { label: '是', value: true },
              { label: '否', value: false },
            ]}
            disabled={!row.editor}
          />
        </Form.Item>
      );
    },
  },
  {
    name: '申报发电电力(MWh)',
    code: 'declaredGenerationCapacity',
    align: 'center',
    render: (value: any, row: any) => {
      return row.editor ? (
        <Form.Item name={`declaredGenerationCapacity@${row.month}`}>
          <InputNumber precision={3} />
        </Form.Item>
      ) : (
        value
      );
    },
  },
  {
    name: '发电能力曲线情况',
    code: 'generationCapacityCurve',
    align: 'center',
    render: (value: any, row: any) => {
      return row.editor ? (
        <Form.Item name={`generationCapacityCurve@${row.month}`}>
          <Input />
        </Form.Item>
      ) : (
        value
      );
    },
  },
  {
    name: '近三年上限(MWh)',
    code: 'threeYearUpperLimit',
    align: 'center',
    render: (value: any, row: any) => {
      return row.editor ? (
        <Form.Item name={`threeYearUpperLimit@${row.month}`}>
          <Input />
        </Form.Item>
      ) : (
        value
      );
    },
  },
  {
    name: '近三年下限 (MWh)',
    code: 'threeYearLowerLimit',
    align: 'center',
    render: (value: any, row: any) => {
      return row.editor ? (
        <Form.Item name={`threeYearLowerLimit@${row.month}`}>
          <Input />
        </Form.Item>
      ) : (
        value
      );
    },
  },
];

const buildInitTableData = (editor: boolean) => {
  return _.range(1, 13).map((v: number) => {
    return {
      month: v,
      spotStrategyStation: false,
      declaredGenerationCapacity: undefined,
      generationCapacityCurve: undefined,
      threeYearUpperLimit: undefined,
      threeYearLowerLimit: undefined,
      editor,
    };
  });
};

const MxModalContent: React.FC<IMxModalContentProps> = (props) => {
  const [form] = Form.useForm();
  const [dataSource, setDataSource] = useState<any[]>([]);
  const [type, setType] = useState<string>('add');
  const [options, setOptions] = useState<any[]>([]);

  useEffect(() => {
    if (props.initValue) {
      const flag = true;
      const list = _.get(props.initValue, 'list', buildInitTableData(flag));
      const year = _.get(props.initValue, 'year', undefined);
      const tableObj = arrToFormData(list, 'month');
      let stationIdList = _.get(props.initValue, 'stationIdList', []);

      if (props.type !== 'add') {
        const stations = _.get(props.currentProvinceInfo, 'stations', []);
        const arr = stations.map((v: any) => {
          return {
            label: v.stationName,
            value: v.stationId,
          };
        });
        setOptions(arr);
        stationIdList = stationIdList[0];
      }
      setDataSource(list);
      form.setFieldsValue({ tableObj, stationIdList, year });
      setType(props.type);
    }
  }, [props.initValue]);

  useEffect(() => {
    props.getHandler &&
      props.getHandler(() => {
        return new Promise((resolve, reject) => {
          form
            .validateFields()
            .then((values: any) => {
              const list = formDataToArr(values, dataSource, 'month');
              resolve({
                list,
                stationIdList: props.type === 'add' ? values.stationIdList : [values.stationIdList],
                year: values.year,
              });
            })
            .catch((values: any) => {
              reject(values);
            });
        });
      });
  });

  return (
    <div className="mx-modal-content">
      <TjForm
        form={form}
        items={[
          {
            label: '结算单元',
            name: 'stationIdList',
            render: () =>
              type === 'add' ? (
                <TjMarketingUnit treeData={props.treeData} marketId={props.marketId} />
              ) : (
                <Select options={options} disabled />
              ),
            rules: [{ required: true, message: '请选择结算单元' }],
          },
          {
            label: '年份',
            name: 'year',
            render: (
              <DatePicker
                picker="year"
                style={{ width: '100%' }}
                disabled={type === 'view' ? true : false}
              />
            ),
            rules: [{ required: true, message: '请选择年份' }],
          },
          {
            name: 'list',
            render: (
              <div className="table-box">
                <TjTable columns={columns} dataSource={dataSource} />
              </div>
            ),
            wrapperCol: { span: 24 },
          },
        ]}
      />
    </div>
  );
};

interface IMxModalContentProps {
  treeData: any[];
  marketId?: string;
  initValue?: any;
  getHandler?: (fn: () => Promise<any>) => void;
  type: string;
  currentProvinceInfo?: any;
}

export default MxModalContent;
